import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:hotpot/utils/user_utils.dart';
import 'package:odoo_rpc/odoo_rpc.dart';

// const appDebugMode = kDebugMode;
// const baseurl = appDebugMode ? 'https://hotpot.intpv.es/' : 'https://hotpot.intpv.es/';
// const baseWss = appDebugMode ? 'wss://hotpot.intpv.es/websocket' : 'wss://hotpot.intpv.es/websocket';
// var orpc = OdooClient(baseurl);

class OdooHelper {
  static OdooSession? _session;

  static String? get sessionId => _session?.id;

  static int? get partnerId => _session?.partnerId;

  static get context => {
        "lang": _session?.userLang,
        "tz": _session?.userTz,
        "uid": _session?.userId,
        "allowed_company_ids": [int.parse(UserUtils.partner.companyId!.first)]
      };

  static late OdooClient orpc;
  static late String baseWss;
  static late String baseurl;

  /// 设置域名
  static Future initClient(String baseurl) async {
    if (!baseurl.endsWith('/')) {
      baseurl += '/';
    }
    orpc = OdooClient(OdooHelper.baseurl = baseurl);
    baseWss = '${baseurl}websocket'.replaceFirst('http', 'ws');
  }

  /// 设置数据库，登录账号，密码
  static Future<bool> init(String db, String name, String pws) async {
    try {
      _session = await orpc.authenticate(db, name, pws);
    } catch (_) {}
    return _session != null;
  }

  /// 搜索
  static Future<dynamic> search(
    String model, {
    Map<String, dynamic>? arg,
    Map<String, dynamic> domain = const {},
    Map<dynamic, dynamic> domainLike = const {},
    int? pageSize,
    int? pageNo,
    List<String> fields = const [],
    bool showLoading = false,
  }) {
    if (showLoading) {
      SmartDialog.showLoading();
    }
    var domainList = <dynamic>[];
    for (var item in domain.entries) {
      domainList.add([item.key, '=', item.value]);
    }
    if (domainLike.entries.isNotEmpty) {
      var count = 0;
      for (var item in domainLike.entries) {
        if (item.value is List) {
          count += (item.value as List).length;
        } else {
          count++;
        }
      }
      List.generate(count - 1, (index) => domainList.add('|'));
    }
    for (var item in domainLike.entries) {
      if (item.value is List) {
        for (var i in item.value) {
          domainList.add([item.key, 'ilike', i]);
        }
      } else {
        domainList.add([item.key, 'ilike', item.value]);
      }
    }
    return orpc.callKw({
      'model': model,
      'method': 'search_read',
      'args': [if (arg != null) arg],
      'kwargs': {
        'context': {'bin_size': false},
        'domain': domainList,
        'fields': fields,
        if (pageSize != null) 'limit': pageSize,
        if (pageNo != null && pageSize != null) 'offset': (pageNo - 1) * pageSize,
      },
    }).whenComplete(() {
      if (showLoading) {
        SmartDialog.dismiss();
      }
    });
  }

  /// 调用自定义方法
  static Future<dynamic> callMethod(
    String model,
    String method, {
    Map<String, dynamic>? arg,
    int? id,
    bool showLoading = false,
  }) {
    if (showLoading) {
      SmartDialog.showLoading();
    }
    return orpc.callKw({
      'model': model,
      'method': method,
      'args': [if (id != null) id, if (arg != null) arg],
      'kwargs': {},
    }).whenComplete(() {
      if (showLoading) {
        SmartDialog.dismiss();
      }
    });
  }

  /// 更新
  static Future<dynamic> update(
    String model, {
    Map<String, dynamic>? arg,
    int? id,
    bool showLoading = false,
  }) {
    if (showLoading) {
      SmartDialog.showLoading();
    }
    return orpc.callKw({
      'model': model,
      'method': 'write',
      'args': [if (id != null) id, if (arg != null) arg],
      'kwargs': {},
    }).whenComplete(() {
      if (showLoading) {
        SmartDialog.dismiss();
      }
    });
  }

  /// 创建
  static Future<dynamic> create(
    String model, {
    Map<String, dynamic> arg = const {},
    List<Map<String, dynamic>> argList = const [],
    bool showLoading = false,
  }) {
    if (showLoading) {
      SmartDialog.showLoading();
    }
    return orpc.callKw({
      'model': model,
      'method': 'create',
      'args': [if (argList.isNotEmpty) argList, if (argList.isEmpty) arg],
      'kwargs': {},
    }).whenComplete(() {
      if (showLoading) {
        SmartDialog.dismiss();
      }
    });
  }
}
